#ifndef XCOM_UTILS_H
#define XCOM_UTILS_H
#include "cmdvalue.h"
#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <ranges>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

namespace libxcom {

std::string trim(std::string str);
// 将单个字符转换为对应的BCD码（高位在前）
unsigned char CharToBcd(char h, char l);

// 将std::string转换为BCD编码，结果存储在std::vector<unsigned char>中
std::vector<unsigned char> StringToBcd(const std::string& str);

libxcom::CmdValue VectorToCmd(const std::vector<uint8_t>& vec, bool reverse = false);

std::string BcdToChar(unsigned char bcd);

std::string BcdToString(const CmdValue& bcd);

template<class T>
T HexToBcd(const T& t)
{
    T r = 0;
    T src = t;
    int shift = 0;
    while (src > 0 && shift < sizeof(t) * 8) {
        r |= (src % 10) << shift;
        src /= 10;
        shift += 4;
    }
    return r;
}

template<class T>
libxcom::CmdValue HexToCmd(const T& t, bool reverse = false)
{
    libxcom::CmdValue cmd;
    uint8_t* src = reinterpret_cast<uint8_t*>(const_cast<T*>(&t));
    if (reverse) {
        for (int32_t i = sizeof(t) - 1; i >= 0; i--) {
            cmd += src[i];
        }
    } else {
        for (int32_t i = 0; i < sizeof(t); i++) {
            cmd += src[i];
        }
    }
    return cmd;
}
}; // namespace libxcom
#endif
